package cc.zy.base.businesses.utils;

import com.alibaba.fastjson.JSONObject;
import com.ec.v2.config.Config;
import com.ec.v2.entity.config.*;
import com.ec.v2.entity.customer.CrmIdslDto;
import com.ec.v2.entity.customer.QueryLabelResp;
import com.ec.v2.entity.sales.GetSalesVO;
import com.ec.v2.entity.sales.SalesMoneyArrayDTO;
import com.ec.v2.entity.sales.SalesResponse;
import com.ec.v2.service.Customer;
import com.ec.v2.service.Sales;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * EC数据获取类
 *
 * @author peihaodong
 * @version 1.0
 * @date 2021/1/29 19:21
 */
@Slf4j
public class ECUtil {

    //EC API的配置信息
    private static long corpId = 15274436;
    private static String appId = "705715394396028928";
    private static String secret = "QBNKUtgRznRmTU6iEFC";
    private static ECUtil ecUtil = new ECUtil();

    //私有化构造
    private ECUtil() {

    }

    //静态获取单例
    public static ECUtil getInstance() {
        return ecUtil;
    }

    //加载时进行初始化配置
    static {
        // 初始化配置信息
        Config.initConfig(corpId, appId, secret);
        log.info("初始化配置");
        log.info("corpId=" + corpId);
        log.info("appId=" + appId);
        log.info("secret=" + secret);
    }

    public static void setCorpId(long corpId) {
        ECUtil.corpId = corpId;
        // 初始化配置信息
        Config.initConfig(corpId, appId, secret);
    }

    public static void setAppId(String appId) {
        ECUtil.appId = appId;
        // 初始化配置信息
        Config.initConfig(corpId, appId, secret);
    }

    public static void setSecret(String secret) {
        ECUtil.secret = secret;
        // 初始化配置信息
        Config.initConfig(corpId, appId, secret);
    }

    public static long getCorpId() {
        return corpId;
    }

    public static String getAppId() {
        return appId;
    }

    public static String getSecret() {
        return secret;
    }

    /**
     * 从EC系统获取所有标签信息
     */
    public Map<Long, Map<String, String>> getLableMap() {

        Map<Long, Map<String, String>> labelMap = new HashMap<Long, Map<String, String>>();

        //执行查询
        ConfigResponse<ConfigCrmGroupTagResp> res = null;
        List<ConfigCrmGroupTagResp> list = null;
        try {
            res = com.ec.v2.service.Config.getLabelInfo();
            list = res.getData();
        } catch (IOException e) {
            e.printStackTrace();
        }

        for (ConfigCrmGroupTagResp labelGroupList : list) {
            String labelGroupName = labelGroupList.getLabelGroupName();
            List<ConfigCrmTagResp> labelList = labelGroupList.getLabelList();
            for (ConfigCrmTagResp label : labelList) {
                Long labelId = label.getLabelId();
                String labelName = label.getLabelName();
                Map<String, String> map = new HashMap<String, String>();
                map.put(labelGroupName, labelName);
                labelMap.put(labelId, map);
            }
        }

        return labelMap;
    }

    /**
     * 根据客户id  crmId  获取标签id集合
     */
    public List<Integer> getLabelIds(Long crmId) {

        String crmIdStr = crmId.toString();

        // 2. 构建请求参数
        CrmIdslDto dto = new CrmIdslDto();
        dto.setCrmIds(crmIdStr);
        // 3. 请求服务器 获取数据
        QueryLabelResp res = null;
        try {
            // 4。 处理结果
            res = Customer.queryLabel(dto);
        } catch (IOException e) {
            e.printStackTrace();
        }

        String labelIdsStr = res.getData().get(0).getLabelIds();
        String[] strArray = labelIdsStr.split(",");
        List<Integer> labelIds = new ArrayList<Integer>();
        for (String s : strArray) {
            int i = Integer.parseInt(s);
            labelIds.add(i);
        }

        return labelIds;
    }

    /**
     * 从EC系统获取所有自定义字段信息
     */
    public Map<Integer, Map<String, String>> getFieldInfoMap() {

        ConfigResponse<ConfigCustomFieldResp> res = null;
        try {
            res = com.ec.v2.service.Config.getFieldMapping();
        } catch (IOException e) {
            e.printStackTrace();
        }

        Map<Integer, Map<String, String>> fieldInfoMap = new HashMap<Integer, Map<String, String>>();
        for (ConfigCustomFieldResp configCustomFieldResp : res.getData()) {
            String fieldName = configCustomFieldResp.getFieldName();
            List<ConfigCustomFieldParamResp> fieldParam = configCustomFieldResp.getFieldParam();
            Map<String, String> map = new HashMap<String, String>();
            if (fieldParam != null) {
                for (ConfigCustomFieldParamResp configCustomFieldParamResp : fieldParam) {
                    Integer paramId = configCustomFieldParamResp.getParamId();
                    String paramName = configCustomFieldParamResp.getParamName();
                    map.put(fieldName, paramName);
                    fieldInfoMap.put(paramId, map);
                }
            } else {
                map.put(fieldName, "");
                fieldInfoMap.put(null, map);
            }
        }

        return fieldInfoMap;
    }

    /**
     * 方法描述：根据最后更新时间查询订单状态为结单的EC数据
     *
     * @param startDate
     * @param endDate
     * @return java.util.List<com.ec.v2.entity.sales.SalesResponse<com.ec.v2.entity.sales.SalesMoneyArrayDTO>> 请求响应的集合
     * @author LiPeng
     * @date 2021/3/14
     */
    public List<SalesResponse<SalesMoneyArrayDTO>> getData(Date startDate, Date endDate) {

        log.debug(String.format("startDate = %1$s", startDate));
        log.debug(String.format("endDate = %1$s", endDate));

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = dateFormat.parse("1970-01-01 00:00:00");
        } catch (ParseException e) {
            e.printStackTrace();
        }

        //起始时间为计算机元年，将起始结束时间设为null；否则不变
        if (startDate.equals(date)) {
            startDate = null;
            endDate = null;
        }

        //如果起始结束都不为null，将起始时间减少一分钟，防止网络延迟
        String startDateStr = null;
        String endDateStr = null;
        if (startDate != null && endDate != null) {
            startDate = new Date(startDate.getTime() - 60 * 1000);
            startDateStr = dateFormat.format(startDate);
            endDateStr = dateFormat.format(endDate);
        }
        log.debug(String.format("startDateStr = %1$s", startDateStr));
        log.debug(String.format("endDateStr = %1$s", endDateStr));

        GetSalesVO getSalesVO = new GetSalesVO();
        getSalesVO.setSalesStatus(3);//3为结单状态  {2：发现机会  3：结单  4：无效}
        StringBuilder stringBuilder = new StringBuilder();
        getSalesVO.setLastModifyTime((startDateStr != null && endDateStr != null) ? stringBuilder.append(startDateStr)
                .append(";").append(endDateStr).toString() : null);

        SalesResponse<SalesMoneyArrayDTO> response = null;
        try {
            response = Sales.getSales(getSalesVO);

            log.debug(String.format("response = %s", response));

            List<SalesResponse<SalesMoneyArrayDTO>> responseList = new ArrayList<>();
            responseList.add(response);
            if (response != null && response.getData() != null) {
                for (int i = 2; i <= response.getData().getMaxPageNo(); i++) {
                    getSalesVO.setPageNo(i);
                    response = Sales.getSales(getSalesVO);
                    responseList.add(response);
                }
            }
            return responseList;
        } catch (IOException e) {
            log.error("请求EC：获取订单列表失败");
            log.error(e.toString());
            return null;
        }
    }

    /**
     * 根据数据库json字符串解析为对象
     *
     * @Retrun SalesResponse<SalesMoneyArrayDTO>
     */
    public SalesResponse<SalesMoneyArrayDTO> parseData(String salesRespJsonStr) {

        SalesResponse salesResponse = JSONObject.parseObject(salesRespJsonStr, SalesResponse.class);
        return salesResponse;
    }
}